package pl.pyjter;

import java.util.HashMap;
import java.util.List;

import javax.swing.JOptionPane;

public class LibraryEngine {
	private HashMap<String, Class> tables;
	private LibraryHibImpl library;
	private HashMap<String, HibernateTableModel> tablesModels;
	private HashMap<String, List> tablesLists;
	
	private String activeTableName;
	
	public LibraryEngine(HashMap<String, Class> tables) throws Throwable {
		this.tables = tables;
		this.library = new LibraryHibImpl();
		
		tablesModels = new HashMap<>();
		tablesLists = new HashMap<>();
		fillTablesModels();
		fillTablesLists();
	}
	
	private void fillTablesModels() throws Throwable {
		for(String tableName : tables.keySet()) {
			HibernateTableModel newTableModel = new HibernateTableModel<>(tables.get(tableName));
			tablesModels.put(tableName, newTableModel);
		}
	}
	
	private void fillTablesLists() throws Throwable {
		for(String tableName : tables.keySet()) {
			List newList = library.getObjects(tableName);
			for(Object object : newList) {
				tablesModels.get(tableName).insertRow(object);
			}
			tablesLists.put(tableName, newList);
		}
	}
	
	public void deleteRow(String table, int id, int index) {
		try {
			library.deleteObject(tables.get(table), id);
			tablesModels.get(table).deleteRow(index);
		} catch (org.hibernate.ObjectDeletedException e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
		} finally {
			
		}
	}
	
	public HashMap<String, Class> getTables() {
		return tables;
	}
	
	public HibernateTableModel getTableModel(String tableName) {
		return tablesModels.get(tableName);
	}
	
	
}
